package com.kandinfo.base.common.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.kandinfo.base.common.dto.ResultDto;
import com.kandinfo.base.common.dto.ResultDtoFactory;

public class PicUploader {

    static private JSch jsch = new JSch();

    static String SFTPHOST;
    static Integer SFTPPORT;
    static String SFTPUSER;
    static String SFTPPASS;
    static String SFTPWORKINGDIR;
    static String TEMPWORKINGDIR;

    static Session session = null;
    static Channel channel = null;
    static ChannelSftp channelSftp = null;

    final static Logger logger = Logger.getLogger(PicUploader.class);

    static {
        // load a properties file
        Map<String, Object> pro = PropertiesParse.properties2Map("/env/env-var.properties");
        /*Properties prop = new Properties();
        InputStream input = new FileInputStream("src/main/resource/env/dev/env-var.properties");
        prop.load(input);*/
        SFTPHOST = (String) pro.get("sftp.host");
        SFTPPORT = Integer.valueOf((String)pro.get("sftp.port"));
        SFTPUSER = (String) pro.get("sftp.username");
        SFTPPASS = (String) pro.get("sftp.password");
        SFTPWORKINGDIR = (String) pro.get("sftp.parentDir");
        TEMPWORKINGDIR=(String) pro.get("sftp.tempDir");

    }
    public PicUploader() {
    }

    public synchronized static ResultDto doUpload(FileInputStream input,String fileName,String subDir) {
    	try {
            if(createDir(subDir)) {//创建文件夹
                upload(input, fileName, subDir);
            }
            return ResultDtoFactory.toAck(fileName + "  文件上传成功");
		} catch (SftpException | IOException e) {
        	logger.error("文件上传异常", e);
            return ResultDtoFactory.toNack(fileName + "  文件上传失败,错误信息：" + e.getMessage());
		}
    }
    
    public static void upload(FileInputStream input,String fileName,String subDir) throws FileNotFoundException, SftpException {
        open();
        channelSftp.cd(subDir);
        channelSftp.put(input,fileName);
        channelSftp.cd("..");
        shutdown();
    }

    public static boolean createDir(String dirname){
        boolean success = false;
        try {
            open();
        	String[] nameArr = dirname.split("/");
        	for (String name : nameArr) {
        		createDirByOne(name);
                channelSftp.cd(name);
			}
        	channelSftp.cd("..");
        	success = true;
        } catch (SftpException e) {
        	logger.error("创建文件夹异常", e);
        } finally {
            shutdown();
		}
		return success;
    }
    
    private static void createDirByOne(String dirName){
    	try{
            channelSftp.ls(dirName);
        }catch(Exception ex){
            try {
            	channelSftp.mkdir(dirName);
            } catch (SftpException e) {
            	logger.error("创建文件夹异常", e);
            }
        }
    }
    
    public static void open() {
        String workingDir=SFTPWORKINGDIR;
        try {
            session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
            session.setPassword(SFTPPASS);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            System.out.println("Host connected.");
            channel = session.openChannel("sftp");
            channel.connect();
            System.out.println("sftp channel opened and connected.");
            channelSftp = (ChannelSftp) channel;
            channelSftp.cd(workingDir);
        } catch (Exception e) {
            logger.error(e.toString());
        }
    }
    public static void shutdown() {
        channelSftp.exit();
        channel.disconnect();
        session.disconnect();
    }
}
